

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

interface FormData {
  emailPhone: string;
  password: string;
  confirmPassword: string;
  agreement: boolean;
}

interface FormErrors {
  emailPhone: string;
  password: string;
  confirmPassword: string;
  agreement: string;
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate();
  
  const [formData, setFormData] = useState<FormData>({
    emailPhone: '',
    password: '',
    confirmPassword: '',
    agreement: false
  });

  const [formErrors, setFormErrors] = useState<FormErrors>({
    emailPhone: '',
    password: '',
    confirmPassword: '',
    agreement: ''
  });

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '注册 - 精进坊';
    return () => { document.title = originalTitle; };
  }, []);

  // 验证函数
  const validateEmailOrPhone = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    return emailRegex.test(value) || phoneRegex.test(value);
  };

  const validatePassword = (value: string): boolean => {
    return value.length >= 8 && /[a-zA-Z]/.test(value) && /\d/.test(value);
  };

  // 显示错误信息
  const showError = (field: keyof FormErrors, message: string) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: message
    }));
  };

  // 隐藏错误信息
  const hideError = (field: keyof FormErrors) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: ''
    }));
  };

  // 处理输入变化
  const handleInputChange = (field: keyof FormData, value: string | boolean) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理输入框失去焦点验证
  const handleEmailPhoneBlur = () => {
    const value = formData.emailPhone.trim();
    if (!value) {
      showError('emailPhone', '请输入邮箱或手机号');
    } else if (!validateEmailOrPhone(value)) {
      showError('emailPhone', '请输入有效的邮箱或手机号');
    } else {
      hideError('emailPhone');
    }
  };

  const handlePasswordBlur = () => {
    const value = formData.password;
    if (!value) {
      showError('password', '请输入密码');
    } else if (!validatePassword(value)) {
      showError('password', '密码至少8位，包含字母和数字');
    } else {
      hideError('password');
    }
  };

  const handleConfirmPasswordBlur = () => {
    const value = formData.confirmPassword;
    const passwordValue = formData.password;
    if (!value) {
      showError('confirmPassword', '请确认密码');
    } else if (value !== passwordValue) {
      showError('confirmPassword', '两次输入的密码不一致');
    } else {
      hideError('confirmPassword');
    }
  };

  // 生成随机用户名
  const generateRandomUsername = (emailPhone: string): string => {
    // 如果是邮箱，使用邮箱前缀
    if (emailPhone.includes('@')) {
      const prefix = emailPhone.split('@')[0];
      return prefix + Math.floor(Math.random() * 1000);
    }
    // 如果是手机号，使用 "user" + 随机数字
    return 'user' + Math.floor(Math.random() * 100000);
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 清除之前的错误信息
    setFormErrors({
      emailPhone: '',
      password: '',
      confirmPassword: '',
      agreement: ''
    });

    // 获取表单数据
    const emailPhone = formData.emailPhone.trim();
    const password = formData.password;
    const confirmPassword = formData.confirmPassword;
    const isAgreed = formData.agreement;

    let hasError = false;

    // 验证邮箱/手机号
    if (!emailPhone) {
      showError('emailPhone', '请输入邮箱或手机号');
      hasError = true;
    } else if (!validateEmailOrPhone(emailPhone)) {
      showError('emailPhone', '请输入有效的邮箱或手机号');
      hasError = true;
    }

    // 验证密码
    if (!password) {
      showError('password', '请输入密码');
      hasError = true;
    } else if (!validatePassword(password)) {
      showError('password', '密码至少8位，包含字母和数字');
      hasError = true;
    }

    // 验证确认密码
    if (!confirmPassword) {
      showError('confirmPassword', '请确认密码');
      hasError = true;
    } else if (password !== confirmPassword) {
      showError('confirmPassword', '两次输入的密码不一致');
      hasError = true;
    }

    // 验证用户协议
    if (!isAgreed) {
      showError('agreement', '请阅读并同意用户协议和隐私政策');
      hasError = true;
    }

    if (hasError) {
      return;
    }

    // 显示加载状态
    setIsSubmitting(true);

    try {
      // 生成随机用户名
      const userName = generateRandomUsername(emailPhone);
      
      // 调用后端注册接口
      const response = await fetch('http://localhost:8121/api/user/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userAccount: emailPhone,
          userPassword: password,
          checkPassword: confirmPassword,
          userName: userName
        }),
      });

      const result = await response.json();

      if (response.ok && result.code === 0) {
        // 注册成功
        alert('注册成功！');
        navigate('/login');
      } else {
        // 注册失败，显示错误信息
        const errorMessage = result.message || '注册失败，请重试';
        showError('emailPhone', errorMessage);
      }
    } catch (error) {
      console.error('注册请求失败:', error);
      showError('emailPhone', '网络错误，请检查网络连接后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 处理键盘导航
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && e.target !== document.querySelector('button')) {
      const inputs = Array.from(document.querySelectorAll('input[required]'));
      const currentIndex = inputs.indexOf(e.target as HTMLInputElement);
      
      if (currentIndex < inputs.length - 1) {
        inputs[currentIndex + 1].focus();
      } else {
        handleSubmit(e);
      }
    }
  };

  // 处理用户协议链接点击
  const handleUserAgreementClick = (e: React.MouseEvent) => {
    e.preventDefault();
    alert('用户协议页面');
  };

  // 处理隐私政策链接点击
  const handlePrivacyPolicyClick = (e: React.MouseEvent) => {
    e.preventDefault();
    alert('隐私政策页面');
  };

  return (
    <div className={styles.pageWrapper} onKeyDown={handleKeyDown}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
        <div className="flex items-center justify-center h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className={`w-10 h-10 ${styles.gradientBg} rounded-xl flex items-center justify-center`}>
              <i className="fas fa-graduation-cap text-white text-lg"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">精进坊</h1>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="pt-16 min-h-screen flex items-center justify-center px-4 py-8">
        <div className="w-full max-w-md">
          {/* 注册表单卡片 */}
          <div className={`${styles.registerCard} rounded-card shadow-card p-8`}>
            {/* 页面标题 */}
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-text-primary mb-2">欢迎加入精进坊</h2>
              <p className="text-text-secondary text-sm">开启你的个人成长之旅</p>
            </div>

            {/* 注册表单 */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 邮箱/手机号输入 */}
              <div className="space-y-2">
                <label htmlFor="email-phone" className="block text-sm font-medium text-text-primary">
                  邮箱或手机号 *
                </label>
                <input
                  type="text"
                  id="email-phone"
                  name="email-phone"
                  value={formData.emailPhone}
                  onChange={(e) => handleInputChange('emailPhone', e.target.value)}
                  onBlur={handleEmailPhoneBlur}
                  className={`w-full px-4 py-3 border rounded-lg ${styles.formInputFocus} transition-all duration-200 ${
                    formErrors.emailPhone ? 'border-red-300' : 'border-gray-200'
                  }`}
                  placeholder="请输入邮箱或手机号"
                  required
                />
                {formErrors.emailPhone && (
                  <div className={styles.errorMessage}>{formErrors.emailPhone}</div>
                )}
              </div>

              {/* 密码输入 */}
              <div className="space-y-2">
                <label htmlFor="password" className="block text-sm font-medium text-text-primary">
                  密码 *
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    id="password"
                    name="password"
                    value={formData.password}
                    onChange={(e) => handleInputChange('password', e.target.value)}
                    onBlur={handlePasswordBlur}
                    className={`w-full px-4 py-3 pr-12 border rounded-lg ${styles.formInputFocus} transition-all duration-200 ${
                      formErrors.password ? 'border-red-300' : 'border-gray-200'
                    }`}
                    placeholder="请输入密码"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-secondary"
                  >
                    <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {formErrors.password && (
                  <div className={styles.errorMessage}>{formErrors.password}</div>
                )}
                <p className="text-xs text-text-secondary">密码至少8位，包含字母和数字</p>
              </div>

              {/* 确认密码输入 */}
              <div className="space-y-2">
                <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">
                  确认密码 *
                </label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    id="confirm-password"
                    name="confirm-password"
                    value={formData.confirmPassword}
                    onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                    onBlur={handleConfirmPasswordBlur}
                    className={`w-full px-4 py-3 pr-12 border rounded-lg ${styles.formInputFocus} transition-all duration-200 ${
                      formErrors.confirmPassword ? 'border-red-300' : 'border-gray-200'
                    }`}
                    placeholder="请再次输入密码"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-secondary"
                  >
                    <i className={`fas ${showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {formErrors.confirmPassword && (
                  <div className={styles.errorMessage}>{formErrors.confirmPassword}</div>
                )}
              </div>

              {/* 用户协议 */}
              <div className="space-y-2">
                <label className="flex items-start space-x-3 cursor-pointer">
                  <input
                    type="checkbox"
                    id="agreement"
                    name="agreement"
                    checked={formData.agreement}
                    onChange={(e) => handleInputChange('agreement', e.target.checked)}
                    className="mt-1 w-4 h-4 text-secondary border-gray-300 rounded focus:ring-secondary focus:ring-2"
                    required
                  />
                  <span className="text-sm text-text-secondary">
                    我已阅读并同意
                    <a
                      href="#"
                      onClick={handleUserAgreementClick}
                      className="text-secondary hover:text-accent underline"
                    >
                      《用户协议》
                    </a>
                    和
                    <a
                      href="#"
                      onClick={handlePrivacyPolicyClick}
                      className="text-secondary hover:text-accent underline"
                    >
                      《隐私政策》
                    </a>
                  </span>
                </label>
                {formErrors.agreement && (
                  <div className={styles.errorMessage}>{formErrors.agreement}</div>
                )}
              </div>

              {/* 注册按钮 */}
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full py-3 bg-secondary text-white rounded-lg font-medium hover:bg-accent focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <span>{isSubmitting ? '注册中...' : '立即注册'}</span>
                {isSubmitting && (
                  <i className="fas fa-spinner fa-spin ml-2"></i>
                )}
              </button>
            </form>

            {/* 底部链接 */}
            <div className="mt-8 text-center">
              <p className="text-text-secondary text-sm">
                已有账号？
                <Link
                  to="/login"
                  className="text-secondary hover:text-accent font-medium"
                >
                  立即登录
                </Link>
              </p>
            </div>
          </div>

          {/* 装饰性元素 */}
          <div className="absolute inset-0 pointer-events-none overflow-hidden">
            <div className="absolute top-20 left-10 w-32 h-32 bg-primary opacity-20 rounded-full"></div>
            <div className="absolute bottom-20 right-10 w-24 h-24 bg-secondary opacity-10 rounded-full"></div>
            <div className="absolute top-1/2 left-1/4 w-16 h-16 bg-accent opacity-5 rounded-full"></div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default RegisterPage;

